package cn.wen.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

public class IdentifyCodeUtil
{
	public static final int WIDTH = 60;
	public static final int HEIGHT = 20;
	public static final int SIZE = 4;
	private String codeStr;

	/**
	* @Title: generteCode
	* @Description: TODO(这里用一句话描述这个方法的作用)
	* @return ByteArrayInputStream    返回类型
	* @throws
	*/
	public ByteArrayInputStream generteCode()
	{
		codeStr = RandomUtil.getRandeomString(SIZE);

		// 创建图片
		BufferedImage img = new BufferedImage(WIDTH, HEIGHT,
				BufferedImage.TYPE_INT_RGB);
		// 获取图片上下文
		Graphics grap = img.getGraphics();

		// 设置填充区
		grap.setColor(Color.white);
		grap.fillRect(0, 0, WIDTH, HEIGHT);

		// 添加干扰
		Disruptor disruptor = new LineDisruptor(); // 添加干扰线
		grap = disruptor.getDisruptor(grap, 10);

		disruptor = new PointDisruptor();
		grap = disruptor.getDisruptor(grap, 100); // 添加干扰点

		// 填充字符串到填充区
		grap.setFont(new Font(null, Font.PLAIN, 18));
		grap.setColor(Color.black);
		grap.drawString(codeStr, 10, 17);

		// System.out.println(codeStr);

		// 完成
		grap.dispose();

		ByteArrayInputStream input = null;
		try
		{
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			// 设置输出目标为：output
			ImageOutputStream imageOut = ImageIO
					.createImageOutputStream(output);
			// 把 img对象 写入到 imageOut中
			ImageIO.write(img, "JPEG", imageOut);
			imageOut.close();
			// 获取输出流对象 返回
			input = new ByteArrayInputStream(output.toByteArray());
		} catch (Exception e)
		{
			System.out.println("产生验证码出错：" + e.toString());
		}

		// 返回输出流
		return input;

	}

	public String getCodeStr()
	{
		return codeStr;
	}

	public void setCodeStr(String codeStr)
	{
		this.codeStr = codeStr;
	}
}
